package hn.cch.redis_token.service;

import hn.cch.redis_token.constant.TokenConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * token  业务处理
 */

@Service
public class TokenService {

    private static Logger logger = LoggerFactory.getLogger(TokenService.class);


    @Autowired
    private RedisService redisService;

    /**
     * 利用UUID生成唯一主键并拼接固定前缀组成redis键值
     * @return
     */
    public String createToken(){
        String uuid = UUID.randomUUID().toString();
        redisService.setObjectExpire(uuid,
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date()), TokenConstant.TOKEN_EXPIRE_TIME);
        logger.info("uuid:{}", uuid);
        return uuid;
    }

    /**
     * 从请求头部中取出token
     * 查询redis校验token
     * @param httpServletRequest
     * @return
     */
    public boolean verifyToken(HttpServletRequest httpServletRequest){

        String token = httpServletRequest.getHeader(TokenConstant.TOKEN_HEADER_NAME);
        logger.info("token:{}", token);
        if (StringUtils.isEmpty(token)){
            logger.info("isEmpty");
            return false;
        }
        if (!redisService.has(token)){
            logger.info("hasFalse");
            return false;
        }
        if (!redisService.del(token)){
            logger.info("delFalse");
            return false;
        }
        return true;
    }

}
